#include "thread_pool.h"
#include <mysql/mysql.h>
#include <string.h>

extern MYSQL* conn;

void cdCommand(task_t * task)
{
    printf("execute cdCommand.\n");
    //获取userid
    int userid = -1;
    getUserid(task->peerfd, &userid);
    printf("userid: %d\n", userid);

    //获取用户传来的filename
    char filename[128] = {0};
    strcpy(filename, task->data);
    printf("filename: %s\n", filename);

    //查询当前的pwdid
    int pwdid = -1;
    char query[512] = {0};
    sprintf(query,
            "SELECT pwdid FROM t_user WHERE userid=%d",
            userid);
    mysql_query(conn, query);
    MYSQL_RES* res = mysql_store_result(conn);
    MYSQL_ROW row = mysql_fetch_row(res);
    pwdid = atoi(row[0]);
    mysql_free_result(res);
    printf("pwdid: %d\n", pwdid);

    //查询该pwd下是否有这个要进入的文件夹，并拿到其fid
    memset(query, 0, sizeof(query));
    sprintf(query,
            "SELECT fid FROM t_file WHERE owner_id=%d AND parent_id=%d AND filename='%s' AND type='d'",
            userid, pwdid, filename);
    printf("query1: %s\n", query);
    mysql_query(conn, query);
    res = mysql_store_result(conn);
    int count = mysql_num_rows(res);
    printf("count: %d\n", count);

    if(count == 0 && (strcmp(filename, ".."))){     //文件夹不存在
        fprintf(stderr, "Dir is not exists.\n");
        sendMsg(task->peerfd, MSG_TYPE_NOT_EXIST, "Dir is not exists.");
        return;
    }

    if(pwdid == 0 && (!strcmp(filename, ".."))){     //目录为根还想cd..
        fprintf(stderr, "Error: You are already in the topmost directory.\n");
        sendMsg(task->peerfd, MSG_TYPE_NOT_EXIST, "Error: You are already in the topmost directory.");
        return;
    }

    //拿到这个文件夹的fid
    int fid = -1;
    if(count == 1){     //文件夹存在，拿到其fid
        row = mysql_fetch_row(res);
        fid = atoi(row[0]);
        mysql_free_result(res);
    } else{     //文件夹为..拿到当前目录的父目录id
        mysql_free_result(res);
        memset(query, 0, sizeof(query));
        sprintf(query,
                "SELECT parent_id FROM t_file WHERE fid=%d",
                pwdid);
        printf("query2: %s\n", query);
        mysql_query(conn, query);
        res = mysql_store_result(conn);
        row = mysql_fetch_row(res);
        fid = atoi(row[0]);
        mysql_free_result(res);
    }
    printf("fid: %d\n", fid);


    char pwd[256] = {0};    //存放最终路径


    //得到想要cd的目录的目录栈
    DirStack ds;
    initDirStack(&ds);
    char tempname[128] = {0};
    int temp_pwdid = fid;
    while(temp_pwdid != 0){
        memset(query, 0, sizeof(query));
        sprintf(query,
                "SELECT parent_id,filename FROM t_file WHERE fid=%d",
                temp_pwdid);
        printf("11query: %s\n", query);
        mysql_query(conn, query);
        res = mysql_store_result(conn);
        row = mysql_fetch_row(res);
        temp_pwdid = atoi(row[0]);
        strcpy(tempname, row[1]);
        pushDirStack(&ds, tempname);
        mysql_free_result(res);
    }

    getDirPath(&ds, pwd);
    destroyDirStack(&ds);
    printf("cd_pwd: %s\n", pwd);

    //将数据写入表中
    memset(query, 0, sizeof(query));
    sprintf(query,
            "UPDATE t_user SET pwd='%s',pwdid=%d WHERE userid=%d",
            pwd, fid, userid);
    printf("query: %s\n", query);
    if(mysql_query(conn, query)){
        fprintf(stderr, "%s\n", mysql_error(conn));
    }

    int affected_row = mysql_affected_rows(conn);
    if(affected_row == 1){
        printf("Update successfully.\n");
        sendMsg(task->peerfd, MSG_TYPE_SUCCESS, pwd);
    } else {
        printf("Error: Fail to update.\n");
        sendMsg(task->peerfd, MSG_TYPE_FAILURE, 
                "An error occurred while updating database.");
    }

}



//2期功能
void cdCommand1(task_t * task)
{
    char path[128] = {0};
    int ret = chdir(task->data);
    if(ret == -1)
    {
        train_t t;
        memset(&t, 0, sizeof(t));
        strcpy(t.buff, "cd error.");
        t.len = strlen(t.buff);
        sendn(task->peerfd, &t, 4 + t.len);
        syslog(LOG_WARNING, "User execute CD command: FAILED.");
        return;
    }
    getcwd(path, 128);
    train_t t;
    memset(&t, 0, sizeof(t));
    strcpy(t.buff, path);
    t.len = strlen(t.buff);
    sendn(task->peerfd, &t, 4 + t.len);

    syslog(LOG_INFO, "User execute CD command: SUCCESSFUL.");
    printf("execute cd command.\n");
}
